package service

import (
	"gobase/app/model"
	"gobase/util"

	"github.com/Sirupsen/logrus"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"github.com/xormplus/xorm"
)

type OrgService struct {
	dao *xorm.Engine
	log *logrus.Logger
}

//初始化方法
func NewOrgService(c *gin.Context) *OrgService {
	return &OrgService{dao: util.GetDb(c), log: util.GetLog(c)}
}

//机构列表
func (srv *OrgService) QueryList() []*model.Org {
	db := srv.dao
	var OrgList []*model.Org

	listSQL := "select t.* from Org as t order by parent_id asc,sortnum asc"
	//查询列表
	err := db.SQL(listSQL).Desc("t.id").Find(&OrgList)

	if err != nil {
		srv.log.Errorf("OrgService->QueryList 列表查询错误：%s", err)
	}
	return OrgList
}

//机构列表--全为可用状态
func (srv *OrgService) GetNoDisableList() []*model.Org {
	db := srv.dao
	var OrgList []*model.Org

	listSQL := "select t.* from Org as t where t.state=1 order by parent_id asc,sortnum asc"
	//查询列表
	err := db.SQL(listSQL).Desc("t.id").Find(&OrgList)

	if err != nil {
		srv.log.Errorf("OrgService->GetNoDisableList 列表查询错误：%s", err)
	}
	return OrgList
}

//新增机构
func (srv *OrgService) Add(Org *model.Org) error {
	//设置Level 值
	if Org.ParentId == 0 {
		Org.Level = 1
	} else {
		pOrg, _ := srv.GetByID(Org.ParentId)
		Org.Level = pOrg.Level + 1
	}

	_, err := srv.dao.Insert(Org)
	if err != nil {
		return errors.Wrap(err, "新增机构失败!")
	}
	return nil
}

//更新机构信息
func (srv *OrgService) Update(id int, Org *model.Org) error {
	//设置Level 值
	if Org.ParentId == 0 {
		Org.Level = 1
	} else {
		pOrg, _ := srv.GetByID(Org.ParentId)
		Org.Level = pOrg.Level + 1
	}

	_, err := srv.dao.Id(id).Cols("name,state,level,parent_id,sortnum,remark").Update(Org)
	if err != nil {
		return errors.Wrap(err, "更新机构信息失败！")
	}
	return nil
}

//删除机构信息
func (srv *OrgService) DeleteByID(id int) error {
	_, err := srv.dao.Id(id).Delete(new(model.Org))
	if err != nil {
		return errors.Wrap(err, "删除机构信息失败!")
	}
	return nil
}

//根据ID查询一条记录,Map返回值
func (srv *OrgService) GetMapByID(id int) (map[string]string, error) {
	var rMap = make(map[string]string)
	_, err := srv.dao.Sql("SELECT t.Id, t.`name` AS Name, t.State, t.Sortnum, t.Remark, ifnull(p.`name`,'') AS ParentName FROM Org t LEFT JOIN Org AS p ON p.parent_id = t.id where t.id=?", id).Get(&rMap)
	if err != nil {
		return rMap, errors.Wrap(err, "获取机构map信息失败!")
	}
	return rMap, nil
}

//根据ID查询一条记录,Map返回值
func (srv *OrgService) GetByID(id int) (model.Org, error) {
	var org model.Org
	_, err := srv.dao.Sql("select t.* from Org as t where t.id=?", id).Get(&org)
	if err != nil {
		return org, errors.Wrap(err, "获取机构map信息失败!")
	}
	return org, nil
}
